<template>
  <div class="duty_list">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item">
          <span class="search-label">角色名称:</span>
          <Input v-model="dataParmas.roleName"
                 @on-keyup="filterSpace"
                 :maxlength="100"
                 placeholder="请输入">
          </Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">角色状态:</span>
          <Select v-model="dataParmas.status"
                  @on-change="selectStatus">
            <Option v-for="item in value2"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="searchList">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item">
          <Button class="search-btn"
                  @click="skipLead"
                  v-if="hasPermission('moms:role:import')">导入</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  v-if="hasPermission('moms:role:export')"
                  :disabled='this.data.length>0 ? false: true'
                  @click='exportData'>导出</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="addShow()"
                  v-if="hasPermission('moms:role:create')">添加</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <Drawer v-model="Dmodal"
            title="复制角色"
            :mask-closable="true"
            class="shopDrawer"
            @on-close="closed"
            width="540">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="100"
            class="shopDrawer_form">
        <FormItem label="角色名称:"
                  prop="roleName">
          <Input v-model="formValidate.roleName"
                 :maxlength="100"
                 @on-keyup="changeName"
                 placeholder="最多输入100字"
                 class="popupcontent_input"></Input>
        </FormItem>
        <FormItem class="shopDrawer_form_btn">
          <Button @click="handleReset"
                  style="width:72px">取消</Button>
          <Button type="primary"
                  @click="handleSubmit"
                  style="width:72px;margin-left:20px">确认</Button>
        </FormItem>
      </Form>
    </Drawer>
    <Table stripe
           :height="this.tableHeight"
           class="table-list"
           ref="selection"
           :loading="loading"
           :columns="columns"
           @on-selection-change="selectOption"
           :data="data">
      <template slot-scope="{ row }"
                slot="member">
        <span v-if="!hasPermission('moms:role:member')">{{ row.userCount }}</span>
        <span class="active"
              @click="skipEmployee(row)"
              v-if="hasPermission('moms:role:member')">{{ row.userCount }}</span>
      </template>
      <template slot-scope="{ row }"
                slot="desc">
        <p class="collection-productdesc">{{ row.remark }}</p>
      </template>
      <template slot-scope="{ row, index }"
                slot="status">
        <span>
          <i-switch v-model="row.status"
                    :disabled="hasPermission('moms:role:updatestatus') && row.roleKey !== 'ROLE_ADMIN'? false : true "
                    @on-change="change(row,index)">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </span>
      </template>
      <template slot-scope="{ row }"
                slot="action">
        <i class="iconsys icondetail"
           @click="look(row.id)"
           title="查看详情"
           v-if="hasPermission('moms:role:detail')">
        </i>
        <i class="iconsys icongongneng"
           @click="setting(row.id)"
           title="功能权限">
        </i>
        <i class="iconsys iconedit"
           @click="lookdetail(row.id)"
           title="编辑"
           v-if="hasPermission('moms:role:update')">
        </i>
        <i class="iconsys iconfuzhi"
           @click="copy(row)"
           title="复制"
           v-if="hasPermission('moms:role:copy') && row.roleKey !== 'ROLE_ADMIN'">
        </i>
        <Poptip confirm
                title="你确定要删除吗？"
                @on-ok="ok(row.id,row.status)"
                @on-cancel="cancel">
          <i class="iconsys icondel"
             title="删除"
             v-if="hasPermission('moms:role:delete') && row.roleKey !== 'ROLE_ADMIN'">
          </i>
        </Poptip>
      </template>
    </Table>
    <Row type="flex">
      <Col span="12"
           class="module-menu-nav">
      <Button class="module-menu-margin"
              @click="handleSelectAll"
              v-if="hasPermission(['moms:role:updatestatus', 'moms:role:delete'])">{{btnTitle}}</Button>
      <Dropdown placement="top"
                trigger="click"
                @on-click="DropdownItemn"
                v-if="hasPermission(['moms:role:updatestatus', 'moms:role:delete'])">
        <Button class="check_all">批量操作</Button>
        <DropdownMenu slot="list"
                      style="text-align:center">
          <DropdownItem name="1"
                        v-if="hasPermission('moms:role:updatestatus')">批量关闭</DropdownItem>
          <DropdownItem name="2"
                        v-if="hasPermission('moms:role:updatestatus')">批量开启</DropdownItem>
          <DropdownItem name="3"
                        v-if="hasPermission('moms:role:delete')">批量删除</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      </Col>
      <Col span="12">
      <div class="page-box">
        <Page :total="size"
              :current="dataParmas.pageIndex"
              :page-size="dataParmas.pageSize"
              @on-page-size-change="selectPageNum"
              @on-change="selectPageInde"
              ref="pages"
              show-total
              show-sizer />
      </div>
      </Col>
    </Row>
  </div>
</template>
<script>
import { roleList, enableRole, disableRole, delRole, copyRole, exportRole } from '@/api/system/role'
import { blobToXls } from '@/libs/blobToXls'
export default {
  name: 'role_list',
  components: {},
  data () {
    return {
      tableHeight: 0,
      btnTitle: '全选',
      roleName: null, // 职务名称
      status: true,
      model1: '', // 角色状态
      loading: true,
      isDelete: true,
      // statuslist: [],
      searchRoleName: '',
      dataParmas: {
        'merchantId': this.$store.state.user.merchantId,
        roleName: null,
        pageIndex: 1,
        pageSize: 10,
        status: '-1'
      },
      idList: [],
      Dmodal: false,
      size: 10,
      value: '',
      value2: [
        {
          value: '-1',
          label: '全部'
        },
        {
          value: '1',
          label: '启用'
        },
        {
          value: '0',
          label: '停用'
        }
      ],
      ruleValidate: {
        roleName: [{
          required: true, message: '角色名称不能为空', trigger: 'blur'
        }]
      },
      modal2: false,
      value3: [
        {
          value: 'New York',
          label: '批量启用'
        },
        {
          value: 'London',
          label: '批量禁用'
        },
        {
          value: 'Sydney',
          label: '批量删除'
        }
      ],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '角色名称',
          key: 'roleName'
        },
        {
          title: '角色人员',
          key: 'userCount',
          slot: 'member'
        },
        {
          title: '角色描述',
          key: 'remark',
          slot: 'desc'
        },
        {
          title: '角色状态',
          slot: 'status'
        },
        {
          title: '操作时间',
          key: 'updateTime'
        }
      ],
      formValidate: {
        'merchantId': this.$store.state.user.merchantId,
        roleName: '', // 职务名称
        remark: null, // 角色描述
        id: ''
      },
      data: [
      ]
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'role_list') {
        // this.dataParmas.pageIndex = 1
        this.getRole({ pageIndex: this.dataParmas.pageIndex })
      }
    },
    idList (val) {
      if (val.length === this.data.length && this.data.length !== 0) {
        this.btnTitle = '取消全选'
        this.status = false
      } else {
        this.btnTitle = '全选'
        this.status = true
      }
    }
  },
  computed: {
  },
  mounted () {
    this.getRole({ pageIndex: 1 })
    if (this.hasPermission(['moms:role:detail', 'moms:role:grantfunctionpermission', 'moms:role:copy', 'moms:role:update', 'moms:role:delete'])) {
      this.columns.push({
        title: '操作',
        width: 300,
        slot: 'action'
      })
    }
  },
  methods: {
    // 导出
    exportData () {
      exportRole({
        fileName: 'role',
        type: 'EXCEL'
      }).then(res => {
        if (res.status === 200) {
          blobToXls(res.data, '导出角色列表')
        }
      })
    },
    handleSelectAll () {
      // this.status = !this.status
      this.$refs.selection.selectAll(this.status)
    },
    // 导入
    skipLead () {
      this.$router.push({ name: 'role_import' })
    },
    filterSpace () {
      this.dataParmas.roleName = this.dataParmas.roleName ? this.dataParmas.roleName.replace(/\s+/g, '') : null
    },
    skipEmployee (row) {
      this.$router.push({ name: 'role_employee', params: { id: row.id } })
    },
    // 选择状态
    selectStatus (val) {
      this.dataParmas.pageIndex = 1
      this.getRole({ pageIndex: 1 })
    },
    selectOption (val) {
      // this.idList = val.map(item => {
      //   return { id: item.id, status: item.status }
      // })
      this.idList = val
    },
    DropdownItemn (val) {
      if (this.idList.length > 0) {
        let flag = true
        let arr = []
        this.idList.forEach(item => {
          arr.push(item.id)
          if (item.status) {
            flag = false
          }
        })
        // let param = { 'merchantId': this.$store.state.user.merchantId, idList: arr }
        let param = { load: { 'merchantId': this.$store.state.user.merchantId, idList: arr }, valite: {} }
        this.$Modal.confirm({
          title: val === '1' ? '确认批量关闭吗？' : val === '2' ? '确认批量开启吗？' : '确认批量删除吗？',
          onOk: () => {
            if (val === '1') {
              this.close(param)
            } else if (val === '2') {
              this.open(param)
            } else {
              if (flag) {
                this.del(param)
              } else {
                this.$Message.error('组织为启用状态不可删除')
              }
            }
          },
          onCancel: () => {

          }
        })
      } else {
        this.$Message.error('请至少选择一项')
      }
    },
    close (param) {
      disableRole(param.load).then(res => {
        if (res.status === 200) {
          if (res.data.status === 200) {
            if (param.load.idList) {
              this.data.forEach((ele, idx) => {
                this.idList.forEach(item => {
                  if (ele.id === item.id) {
                    this.$set(this.data[idx], 'status', false)
                  }
                })
              })
              this.$Message.success('批量关闭成功！')
              // this.getRole({ pageIndex: this.dataParmas.pageIndex })
              this.idList = []
            } else {
              this.$set(this.data[param.valite.index], 'status', false)
              this.$Message.success('关闭成功！')
            }
          } else {
            if (param.load.idList) {
            } else {
              this.$nextTick(() => {
                this.$set(this.data[param.valite.index], 'status', !param.valite.status)
              })
            }
            this.$Message.error(`${res.data.error}`)
          }
        }
      })
    },
    open (param) {
      enableRole(param.load).then(res => {
        if (res.status === 200) {
          if (res.data.status === 200) {
            if (param.load.idList) {
              this.data.forEach((ele, idx) => {
                this.idList.forEach(item => {
                  if (ele.id === item.id) {
                    this.$set(this.data[idx], 'status', true)
                  }
                })
              })
              this.$Message.success('批量开启成功！')
              // this.getRole({ pageIndex: 1 })
              this.idList = []
            } else {
              this.$set(this.data[param.valite.index], 'status', true)
              this.$Message.success('开启成功！')
            }
          } else {
            if (param.load.idList) {
            } else {
              this.$nextTick(() => {
                this.$set(this.data[param.valite.index], 'status', !param.valite.status)
              })
            }
            this.$Message.error(`${res.data.error}`)
          }
        }
      })
    },
    del (param) {
      delRole(param.load).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('批量删除成功！')
          this.getRole({ pageIndex: 1 })
          this.idList = []
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    setting (idx) {
      this.$router.push({ name: 'role_setting', params: { id: idx } })
    },
    // 提交
    handleSubmit () {
      this.$refs.formValidate.validate((val) => {
        if (val) {
          copyRole(this.formValidate).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('角色复制成功！')
              this.Dmodal = false
              this.$refs.formValidate.resetFields()
              this.getRole({ pageIndex: 1 })
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    // 取消
    handleReset () {
      this.Dmodal = false
      this.$refs.formValidate.resetFields()
    },
    // 关闭
    closed () {
      this.$refs.formValidate.resetFields()
    },
    changeName () {
      this.formValidate.roleName = this.formValidate.roleName.replace(/\s+/g, '')
    },
    selectPageInde (val) {
      this.dataParmas.pageIndex = val
      this.getRole({ pageIndex: val })
    },
    selectPageNum (num) {
      this.dataParmas.pageSize = num
      this.getRole({ pageIndex: 1 })
    },
    copy (data) {
      this.Dmodal = true
      this.formValidate.remark = data.remark
      this.formValidate.id = data.id
    },
    ok (idx, status) {
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        if (status) {
          this.$Message.error('角色为启用状态不可删除')
          setTimeout(() => {
            this.isDelete = true
          }, 400)
        } else {
          setTimeout(() => {
            delRole({
              'merchantId': this.$store.state.user.merchantId,
              id: idx
            }).then(res => {
              this.isDelete = true
              if (res.data.status === 200) {
                this.$Message.success('删除成功！')
                if (this.dataParmas.pageIndex !== 1) {
                  if (this.size % this.dataParmas.pageIndex === 1) {
                    this.dataParmas.pageIndex = this.dataParmas.pageIndex - 1
                  }
                }
                this.getRole({ pageIndex: this.dataParmas.pageIndex })
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }, 200)
        }
      }
    },
    reset () {
      this.searchRoleName = null
      this.dataParmas.roleName = null
      this.dataParmas.status = '-1'
      this.dataParmas.pageIndex = 1
      this.getRole({ pageIndex: 1 })
    },
    cancel () {
      // this.$Message.success(`删除已取消`)
    },
    // 查询
    searchList () {
      this.searchRoleName = this.dataParmas.roleName
      this.dataParmas.pageIndex = 1
      this.getRole({ pageIndex: 1 })
    },
    change (row, index) {
      // let paramster = { 'merchantId': this.$store.state.user.merchantId, id: row.id }
      let paramster = { load: { 'merchantId': this.$store.state.user.merchantId, id: row.id }, valite: { status: row.status, index: index } }
      this.$set(this.data[index], 'status', row.status)
      if (row.status) {
        this.open(paramster)
      } else {
        this.close(paramster)
      }
    },
    getRole (res) {
      this.loading = true
      this.tableHeight = 0
      roleList({ ...this.dataParmas, roleName: this.searchRoleName, status: this.dataParmas.status === '-1' ? '' : this.dataParmas.status, ...res }).then(res => {
        if (res.data.status === 200) {
          this.idList = []
          this.loading = false
          this.size = res.data.data.total
          this.data = res.data.data.records
          if (res.data.data.records && res.data.data.records.length >= 10) {
            this.tableHeight = 520
          }
          this.data.forEach(ele => {
            ele.status = !!ele.status
          })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    look (idx) {
      this.$router.push({ name: 'role_detail', params: { id: idx } })
    },
    lookdetail (idx) {
      this.$router.push({ name: 'role_edit', params: { id: idx } })
    },
    addShow () {
      this.$router.push({ name: 'role_create' })
    }
  }
}
</script>
<style lang="less" scoped>
.search-box {
  .search-item-left {
    width: 65%;
  }
  .search-item-right {
    width: 35%;
  }
}
.table-list {
  .collection-productdesc {
    max-height: 38px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }
}
</style>
<style>
.shopDrawer .shopDrawer_form {
  width: 380px;
  margin: auto;
  padding-top: 16px;
}
.shopDrawer .shopDrawer_form .shopDrawer_form_btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding-top: 16px;
  border-top: 1px solid #e8eaec;
}
.shopDrawer .shopDrawer_form .shopDrawer_form_btn .ivu-form-item-content {
  text-align: right;
  padding-right: 24px;
}
/* .poptip_del .ivu-poptip-body .ivu-icon {
  left: 18px;
} */
.active {
  color: #2d8cf0;
  /* border-bottom: 1px solid #2d8cf0; */
  cursor: pointer;
}
</style>
